<?php

namespace application\depend;

class Ftpupload
{
    private static $ftpconn = null;
    const FTP_ROOT_PATH = 'gwlogs';

    private static function ftpinit()
    {

        if (self::$ftpconn == null) {

            $ftp_conn = ftp_connect(LOG_FTP_SERVER[0], LOG_FTP_SERVER[1]);
            self::$ftpconn = $ftp_conn;
            try {
                if(false === $ftp_conn){
                    Applog::errorLog([
                       'info' => '连接FTP服务器失败[ftp20]',
                        'ftp_server' => LOG_FTP_SERVER
                    ],__FILE__,__LINE__);
                    return false;
                }else {
                    ftp_login($ftp_conn, LOG_FTP_SERVER[2], LOG_FTP_SERVER[3]);
                    return $ftp_conn;
                }
            } catch (\Exception $e) {
                $er['info'] = $e->getMessage();
                Applog::errorLog($er, $e->getFile(), $e->getLine());
                self::$ftpconn = null;
                return false; // 出错咯
            } // end try
        } else { // end if
            return self::$ftpconn;
        }
    }

    private function createGuid()
    {
        return md5(uniqid(mt_rand(), true));

    }//end

    public function getLocalFileInfo($file = "")
    {
        if (empty($file)) {
            return null;
        }
        return pathinfo($file);
    }

    /**
     * @param string $savename 要保存的文件名
     * @param string $savepath 要保存的FTP路径
     * @param string $localpath 本地路径 - 包括文件名
     */
    public function saveFileToFtp($localpath = "", $savename = "", $savepath = "", $uploadfile = "")
    {
        if (empty($savename)) {
            //  $savename = $this->createGuid(); // 创建文件名 如果不需要改名 这个可以忽略
            $savename = date("Y-m-d_H_i_s");
        }
        if (empty($localpath) || !is_file($localpath)) {
            return [
                'error' => UPLOAD_ERR_NO_FILE,
                'errormessage' => '错误的文件'
            ];
        }
        $ftpconn = self::ftpinit(); // 初始化ftp 连接

        if ($ftpconn == null) {
            return [
                'error' => ERR_FTP_SERVER_CONN_FAIL,
                'errormessage' => 'FTP服务器连接失败！'
            ];
        }//end
        if (empty($savepath)) { // ftp 保存路径 默认保存在根目录
            $savepath = self::FTP_ROOT_PATH . '/' . date("Ym");
        } else {
            $savepath = self::FTP_ROOT_PATH . rtrim($savepath, '/') . '/' . date("Ym");

        } // end else if

        //检测FTP目录
        /*
        $checkroot = $this->checkdir($ftpconn, $savepath);
        if ($checkroot['error'] != ERR_RETURN_OK) {
            return $checkroot;
        }
        */
        $this->mksubdir($ftpconn, $savepath);
        $fileInfo = pathinfo($localpath);   //获取本地文件信息

        //    $fileExt = pathinfo($uploadfile);  //获取文件信息

        $fileInfo['size'] = filesize($localpath);   //文件大小

        /*判断文件类型结束*/

        // $ftp_fullname = $savename . '.' . strtolower($fileExt['extension']); // 保存在FTP服务器的文件名
        // 以guid命名

        $ftp_fullname = $savename;
        // $ftp_fullname = $fileinfo['fileinfo']['basename']; //以原文件名保存
        $ftp_fullpath = '/' . $savepath . '/' . $ftp_fullname; // ftp 全路径
        try {
            $ftp_save = ftp_put($ftpconn, $ftp_fullpath, $localpath,
                FTP_BINARY);   //这种模式不行 就试下另一种
        } catch (\Exception $e) {

            try {
                $ftp_save = ftp_put($ftpconn, $ftp_fullpath, $localpath,
                    FTP_ASCII);
            } catch (\Exception $e) {
                $er['info'] = $e->getMessage();
                $er['p1'] = $ftpconn;
                $er['p2'] = $ftp_fullpath;
                $er['p3'] = $fileInfo;
                Applog::errorLog($er, __FILE__, __LINE__);
                return [
                    'error' => '111',
                    'errormessage' => '上传文件过大，请重新上传 ！'
                ];
            }//end try 2
        }//end try 1

        ftp_close($ftpconn);   //哦  这里关闭了连接了  草   关闭连接 就要设置为null
        self::$ftpconn = null;

        if ($ftp_save) {
            return [
                'error' => ERR_RETURN_OK,
                'errormessage' => '保存成功！',
                'path' => $ftp_fullpath,    // ftp 相对路径  加上文件服务器域名就可以访问
                'size' => $fileInfo['size'],  //文件大小  2016.12.15 添加
                'name' => $ftp_fullname,
                'md5' => md5_file($localpath)
            ];
        } else {
            return [
                'error' => '3',
                'errormessage' => '文件保存失败，请稍候重试！'
            ]; // 上传错误
        }

    }//end


    /**
     * 创建目录 -- 官方方法
     */
    public function mksubdir($ftpconn, $savepath)
    {
        @ftp_chdir($ftpconn, '/');
        $parts = explode('/', $savepath); // 2013/06/11/username
        foreach ($parts as $part) {
            if (!@ftp_chdir($ftpconn, $part)) {
                ftp_mkdir($ftpconn, $part);
                ftp_chdir($ftpconn, $part);
                //  ftp_chmod($ftpconn, 0777, $part);
            }
        }
    }

    /**
     * 创建目录
     *
     * @param string $savepath
     *            要创建的穆里
     * @return boolean 创建状态，true-成功，false-失败
     */
    public function checkdir($ftpconn, $savepath)
    {
        // $dir = $this->rootPath . $savepath;

        if (empty($savepath)) {
            return [
                'error' => '5',
                'errormessage' => '请指定FTP目录'
            ];
        }
        $savepath = rtrim($savepath, '/');
        empty($savepath) && $savepath = "/";
        try {
            if (ftp_chdir($ftpconn, $savepath)) {
                return [
                    'error' => ERR_RETURN_OK
                ];
            }
        } catch (\Exception $e) {
            $err['err-msg'] = $e->getMessage();
            $err['info'] = '改变FTP目录失败:' . $savepath;
            Applog::errorLog($err, __FILE__, __LINE__);
        }

        try {
            if (ftp_mkdir($ftpconn, $savepath)) {
                return [
                    'error' => ERR_RETURN_OK
                ];
            }
        } catch (\Exception $e) {
            $err2['err-msg'] = $e->getMessage();
            $err2['info'] = '创建FTP目录失败:' . $savepath;
            Applog::errorLog($err2, __FILE__, __LINE__);
            if ($savepath != "/") {
                try {
                    $checkPreDir = $this->checkdir($ftpconn, dirname($savepath));
                    if ($checkPreDir['error'] == ERR_RETURN_OK && ftp_mkdir($ftpconn, $savepath)) {
                        return [
                            'error' => ERR_RETURN_OK
                        ];
                    }
                } catch (\Exception $e) {
                    $err3['err-msg'] = $e->getMessage();
                    $err3['info'] = '创建FTP目录又失败:' . $savepath;
                    Applog::errorLog($err3, __FILE__, __LINE__);
                    return [
                        'error' => '4',
                        'errormessage' => 'FTP目录' . $savepath . '创建失败！'
                    ];
                }
            } else {
                return [
                    'error' => '5',
                    'errormessage' => 'FTP目录' . $savepath . '创建失败！' . $e->getMessage()
                ];
            }
        }//end catch
    } // end func


}//end